import website from '@/utils/website';
import { validURL, isHttp } from '@/utils/validate';
import { RouteRecordRaw } from 'vue-router';
import layout from '@/layout/index.vue';
import ParentView from '@/components/ParentView/index.vue'; //routerview组件

// glob形式异步导入组件
const modules = import.meta.glob('../views/**/*.vue');
console.log('modules------', modules);
const propsConfig = website.menu.props;
// 设置路由的key
const propsDefault = {
	label: propsConfig.label || 'label',
	path: propsConfig.path || 'path',
	icon: propsConfig.icon || 'icon',
	children: propsConfig.children || 'children',
	meta: propsConfig.meta || 'meta',
};
const loadView = (view: any) => {
	let res;
	for (const path in modules) {
		const dir = path.split('views')[1].split('.vue')[0];
		if (dir === view) {
			res = () => modules[path]();
		}
	}
	return res;
};

function formatRoute(oMenu: Record<string, any>, first: boolean) {
	// 设置路由的key
	const path = oMenu[propsDefault.path] as string;

	//特殊处理组件
	const pathArr = path.split('/');
	// name不能以index结尾
	const tail = pathArr[pathArr.length - 1] === 'index' ? pathArr[pathArr.length - 2] : pathArr[pathArr.length - 1];
	let name;
	if (first) {
		name = pathArr[1];
	} else {
		name = pathArr[1] + '-' + tail;
	}

	const icon = oMenu[propsDefault.icon];

	const children = oMenu[propsDefault.children];

	const meta = {
		keepAlive: oMenu.keepAlive === '1',
		icon: icon,
		name: oMenu[propsDefault.label],
		menuType: oMenu.menuType
	};
	const isChild = children && children.length;
	let component;
	if (isChild && first) {
		if (path === '/ops-workbench') {
			component = ParentView;
		} else {
			component = layout;
		}
	} else if (isChild && !first) {
		// 判断是否为多层路由
		// component = ParentView;
	} else {
		// 判断是否为最终的页面视图
		component = loadView(path);
	}

	const oRouter: RouteRecordRaw = {
		path: path,
		component: component,
		name: name,
		meta: meta,
		redirect: (() => {
			if (isChild) {
				const path = children[0][propsDefault.path];
				return path.indexOf('http') > -1 ? path.split('#')[1] : path;
			} else return '';
		})(),
		// 处理是否为一级路由
		children: [],
	};
	return oRouter;
}

/**
 * 处理成二级路由
 * @param aMenu 当前菜单
 * @param first 是否是一级路由
 * @param childrenRoute children的路由
 * @returns childrenRoute
 */
function formatChildren(aMenu = [], first: boolean, outsideLink: Array<RouteRecordRaw>, childrenRoute: Array<RouteRecordRaw> = []): RouteRecordRaw[] {
	const routerList: any[] = [];
	const aRouter: Array<RouteRecordRaw> = [];

	if (aMenu.length === 0) return aRouter;
	for (let i = 0; i < aMenu.length; i++) {
		const oMenu: any = aMenu[i];
		if (routerList.includes(oMenu[propsDefault.path])) return aRouter;

		const route = formatRoute(aMenu[i], first);

		const children = oMenu[propsDefault.children];

		const isChild = children && children.length;
		if (route.meta!.menuType === '4') {
			// 外链需要在新窗口打开
			route.component = loadView(route.path);
			outsideLink.push(route); 
			continue;

		} else if (isHttp(route.path)) {
			// 外链需要在新窗口打开
			route.path = route.path.split('#')[1];
			route.component = loadView(route.path);
			outsideLink.push(route);
			continue;
		}
		if (isChild) {
			formatChildren(children, false, outsideLink, childrenRoute);
		}

		childrenRoute.push(route);
	}

	return childrenRoute;
}
/**
 * 菜单处理成路由
 * @param aMenu 当前菜单
 * @param first 是否是一级路由
 * @param outsideLink 外链的路由（需要在新窗口打开，需要添加在一级路由）
 * @returns
 */
export function formatRoutes(aMenu = [], first: boolean, outsideLink: Array<RouteRecordRaw> = []): RouteRecordRaw[] {
	console.log('formatRoutes----------', aMenu);
	const routerList: any[] = []; //用来确保不会有重复的路由
	const aRouter: Array<RouteRecordRaw> = []; //最终的结果

	if (aMenu.length === 0) return aRouter;
	for (let i = 0; i < aMenu.length; i++) {
		const oMenu: any = aMenu[i];
		if (routerList.includes(oMenu[propsDefault.path])) return aRouter;

		const route = formatRoute(aMenu[i], first);

		const children = oMenu[propsDefault.children];

		const isChild = children && children.length;

		const icon = oMenu[propsDefault.icon];
		if (route.meta!.menuType === '4') {
			// 外部链接
			outsideLink.push(route); 
			continue;

		} else if (isHttp(route.path)) {
			// 外部链接
			route.path = route.path.split('#')[1];
			outsideLink.push(route);
			continue;
			// route.
		} else {
			const children1 = !isChild
				? (() => {
						if (first) {
							if (!validURL(route.path)) oMenu[propsDefault.path] = `${route.path}/index`;
							return [
								{
									component: () => {
										return loadView(route.path);
									},
									icon: icon,
									name: route.name,
									meta: route.meta,
									path: 'index',
								},
							];
						}
						return [];
				  })()
				: (() => {
						return formatChildren(children, false, outsideLink);
				  })();
			route.children = children1;
		}

		aRouter.push(route);
	}
	console.log('outsideLink--------------', outsideLink);

	if (first) {
		return aRouter.concat(outsideLink);
	} else {
		return aRouter.concat(outsideLink);
	}
}
